import Utils (tok, at, readDouble)

type Race = (Double, Double)

-- real_dis = speed_t * (t - speed_t) >= d
-- y = t * x - x ^ 2
-- y = - x ^ 2 + t * x
-- let y - d == 0 =>
-- - x ^ 2 + t * x - d == 0
-- delta = b^2 - 2ac = t^2 - 2 * -1 * -d = t^2 - 2d
-- x = (-b += sqrt(delta)) / 2a  
nbSols :: Race -> Int
nbSols (t, d) = 
    x1 - x2 + 1
    where
        x1 = floor   $ (t / 2) + sqrt (t ^ 2 / 4 - (d + 1))
        x2 = ceiling $ (t / 2) - sqrt (t ^ 2 / 4 - (d + 1))

-- Time:      7  15   30
-- Distance:  9  40  200
parseInput1 :: [String] -> [Race]
parseInput1 xs = 
    zip ts ds
    where
        ts        = parseLine (xs !! 0)
        ds        = parseLine (xs !! 1)
        parseLine = map readDouble . tok " " . at 1 . tok ":" 

parseInput2 :: [String] -> Race
parseInput2 xs = 
    (t, d)
    where
        t = parseLine (xs !! 0)
        d = parseLine (xs !! 1)
        parseLine = readDouble . filter (/=' ') . at 1 . tok ":"

main = do
    contents <- readFile "input.txt"

    print $ product . map nbSols . parseInput1 . lines $ contents

    print $ nbSols . parseInput2 . lines $ contents